var app = getApp();
const {
  $Toast
} = require('../../dist/base/index');
var server = require('../../utils/server');
Page({
  data: {
    //pageSize: 1,
    //pageNum: 10,
    filterId: 1,
    classShops: [],
    address: '定位中…',
    scrollDown: false,
    banners: [{
      id: 3,
      img: '../../imgs/shop/banner.jpg',
      url: '',
      name: '百亿巨惠任你抢'
    }, ],
    icons: [
      [{
          id: 1,
          img: '/imgs/index/1.png',
          name: '小吃快餐',
          url: ''
        },
        {
          id: 2,
          img: '/imgs/index/2.png',
          name: '甜点饮品',
          url: ''
        },
        {
          id: 3,
          img: '/imgs/index/3.png',
          name: '火锅',
          url: ''
        },
        {
          id: 4,
          img: '/imgs/index/4.png',
          name: '自助西餐',
          url: ''
        }, {
          id: 5,
          img: '/imgs/index/1.png',
          name: '火锅',
          url: ''
        },
        {
          id: 6,
          img: '/imgs/index/2.png',
          name: '自助西餐',
          url: ''
        }

      ]
    ],
    shops: []
  },

  onLoad: function() {
    let that = this;
    that.setData({
      imgUrl: wx.getStorageSync('imgUrl')
    })
    

    that.getMenu();
    that.setData({
      shops: app.globalData.shops
    })

    //banner
    server.postReq('/mobile/home/banner', function(res) {
      if (res.data.code == 1) {
        that.setData({
          banners: res.data.data
        })
      }
    })


    //定位
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        let uid = wx.getStorageSync('uid');

        that.sendLocation(uid, res.longitude, res.latitude);
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        server.qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function(res) {
            // var cont=res.result.address;

            var add = res.result.address;
            var real = String(add).split("省")[1].split("市")[0];
            that.setData({
              address: real
            })
          },
          fail: function(res) {
            console.log(res);
          },
          complete: function(res) {
            var add = res.result.address;
            var real = String(add).split("省")[1].split("市")[0];
            that.setData({
              address: real
            })
          }
        });

      },
      fail:function(err){
        
        wx.showModal({
          title: '是否授权当前位置',
          content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
          success: function (tip) {
            if (tip.confirm) {
              wx.openSetting({
                success: function (data) {
                
                  if (data.authSetting["scope.userLocation"] === true) {
                    that.handleText("授权成功");
                    that.onLoad();
                  }
                }
              })
            }
            }
        })
     
        
      }
    })
    that.getStore()
  },

  onShow: function() {},
  onScroll: function(e) {
    var that = this;


    var n = Number(that.data.shops.length) * 100 + 116;

    if (e.detail.scrollTop > n && !this.data.scrollDown) {

      this.setData({
        scrollDown: true
      });
      var pageSize = that.data.pageSize;
      pageSize++;
      that.setData({
        pageSize: pageSize
      })
      that.getStore(pageSize);
    } else if (e.detail.scrollTop < n && this.data.scrollDown) {
      this.setData({
        scrollDown: false
      });


    }
  },
  getMenu() {
    let that = this;
    server.postReq('/mobile/home/firstOrder', function(res) {
      if (res.data.code == 1) {
        var arr = new Array();
        var list = res.data.data;

        for (let i in list) {
          var id = list[i].id;
          var index = id % 7 + 1;
          list[i].imgSrc = '../../imgs/index/' + index + '.png';
        }
        arr.push(list);
        that.setData({
          icons: arr
        })
      }

    })
  },
  getStore() {
    var that = this;
    //reconmmentStore
    server.postReq('/mobile/home/allrecommend', function(res) {
      if (res.data.code == 1) {

        var stores = res.data.data;
        // var oldStore=that.data.shops;
        // var newArr = oldStore.concat(stores);

        for (let j in stores) {
          let str = that.disc(stores[j].meetMinus);
          stores[j].mm = str;
        }
        that.setData({
          shops: stores
        })
      }
    })
  },
  MenuShop(e) {
 
    let id = e.currentTarget.dataset.id;
    let that = this;
    wx.getStorage({
      key: 'uid',
      success: function(res) {
        var uid = res.data;
        server.postReq('/mobile/home/classifyShop', {
          classify: id,
          userId: uid
        }, function(res) {
          var stores = res.data.data;
          if(!stores.length){
            that.handleText("无结果");
          }
          for (let j in stores) {
            let str = that.disc(stores[j].meetMinus);
            stores[j].mm = str;
          }
          that.setData({
            classShops: stores
          })
        })
      },
    })
  },
  sendLocation(id, lng, lat) {
    var that = this;
    server.postReq('/mobile/updataUserSite', {
      userId: id,
      siteLongitude: lng,
      siteLatitude: lat
    }, function(res) {
      if (res.data.code == 1) {

      } else {

      }
    })
  },
  tapSearch: function() {
    wx.navigateTo({
      url: 'search'
    });
  },
  toNearby: function() {
    var self = this;
    self.setData({
      scrollIntoView: 'nearby'
    });
    self.setData({
      scrollIntoView: null
    });
  },
  tapFilter: function(e) {
    switch (e.target.dataset.id) {
      case '1':
        this.data.shops.sort(function(a, b) {
          return a.id > b.id;
        });
        break;
      case '2':
        this.data.shops.sort(function(a, b) {
          return a.sales < b.sales;
        });
        break;
      case '3':
        this.data.shops.sort(function(a, b) {
          return a.distance > b.distance;
        });
        break;
    }
    this.setData({
      filterId: e.target.dataset.id,
      shops: this.data.shops
    });
  },
  tapBanner: function(e) {
    var name = e.target.dataset.id;
    wx.showModal({
      title: '提示',
      content: '您点击了“' + name + '”活动链接，暂无活动！',
      showCancel: false
    });

  },
  disc(arr) {
    var flag = "";
    if (Object.prototype.toString.call(arr).split(' ')[1].split(']')[0] != 'Array' || !arr.length) {
      flag = "无满减活动";
    } else {

      for (var i = 0; i < arr.length; i++) {
        let item = "满" + arr[i].meet + "减" + arr[i].minus + ",";
        flag += item;

      }
    }
    return flag;
  },
  handleText(msg) {
    $Toast({
      content: msg
    });
  },
  handleSuccess(successMsg) {
    $Toast({
      content: successMsg,
      type: 'success'
    });
  },
  handleWarning(msg) {
    $Toast({
      content: msg,
      type: 'warning'
    });
  },
  handleError() {
    $Toast({
      content: '错误的提示',
      type: 'error'
    });
  },
  handleLoading() {
    $Toast({
      content: '加载中',
      type: 'loading'
    });
  }
});